import { useEffect, useRef } from 'react'
const { remote } = window.require('electron')
const { Menu, MenuItem } = remote

const useContextMenu = (itemArr, targetSelector) => {
    let clickedElement = useRef(null)
    useEffect(() => {
        const menu = new Menu()
        itemArr.forEach(item => {
            menu.append(new MenuItem(item))
        })
        const handleContextMenu = (e) => {
            if(document.querySelector(targetSelector).contains(e.target)) {
                clickedElement.current = e.target
                menu.popup({ window: remote.getCurrentWindow()})
            }
        }
        document.addEventListener('contextmenu', handleContextMenu)
        return () => {
            document.removeEventListener('contextmenu', handleContextMenu)
        }
         // eslint-disable-next-line
    })
    return clickedElement
}

export default useContextMenu